package com.zjmzxfzhl.modules.purchase.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjmzxfzhl.common.Result;
import com.zjmzxfzhl.common.base.BaseController;
import com.zjmzxfzhl.common.util.FileUtil;
import com.zjmzxfzhl.modules.purchase.controller.dto.PurchaseContractDto;
import com.zjmzxfzhl.modules.purchase.controller.dto.PurchaseContractQueryDto;
import com.zjmzxfzhl.modules.purchase.controller.dto.PurchaseMergeContractDto;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseContractDetailVo;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseContractVo;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseIndentSimpleVo;
import com.zjmzxfzhl.modules.purchase.controller.vo.PurchaseIndentVo;
import com.zjmzxfzhl.modules.purchase.entity.PurchaseContract;
import com.zjmzxfzhl.modules.purchase.entity.PurchasePayment;
import com.zjmzxfzhl.modules.purchase.service.PurchaseContractService;
import com.zjmzxfzhl.modules.purchase.service.PurchasePaymentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.List;

/**
 * Controller
 *
 * @author 庄金明
 */
@RestController
@RequestMapping("/purchase/contract")
public class PurchaseContractController extends BaseController {
    @Autowired
    private PurchaseContractService purchaseContractService;

    @Autowired
    private PurchasePaymentService paymentService;

    /**
     * 自定义查询列表
     *
     * @param contractQueryDto
     * @param current
     * @param size
     * @return
     */
    @RequiresPermissions("purchase:contract:list")
    @GetMapping(value = "/list")
    public Result list(PurchaseContractQueryDto contractQueryDto, @RequestParam Integer current, @RequestParam Integer size) {
        IPage<PurchaseContractVo> pageList = purchaseContractService.list(new Page<PurchaseContractVo>(current, size), contractQueryDto);
        return Result.ok(pageList);
    }

    @RequiresPermissions("purchase:contract:list")
    @GetMapping(value = "/queryById")
    public Result queryById(@RequestParam String id) {
        PurchaseContract purchaseContract = purchaseContractService.getById(id);
        return Result.ok(purchaseContract);
    }

    @RequiresPermissions("purchase:contract:list")
    @GetMapping(value = "/queryDetailById")
    public Result queryDetailById(@RequestParam("contractId") Long contractId) {
        PurchaseContractDetailVo purchaseContract = purchaseContractService.getContractDetail(contractId);
        return Result.ok(purchaseContract);
    }

    @GetMapping(value = "/tempInitPayment")
    public Result tempInitPayment(@RequestParam(value = "paymentId", required = false) Long paymentId) {
        if (null == paymentId) {
            purchaseContractService.initAllPayAmount();
        } else {
            PurchasePayment payment = paymentService.getById(paymentId);
            purchaseContractService.initPayAmount(payment);
        }
        return Result.ok();
    }

    @RequiresPermissions("purchase:contract:list")
    @GetMapping(value = "/queryPayments")
    public Result queryPayments(@RequestParam("contractId") Long contractId) {
        List<PurchasePayment> payments = purchaseContractService.queryPayments(contractId);
        return Result.ok(payments);
    }

    /**
     * @param purchaseContract
     * @return
     * @功能：新增
     */
    @RequiresPermissions("purchase:contract:save")
    @PostMapping(value = "/save")
    public Result save(@Valid @RequestBody PurchaseContract purchaseContract) {
        purchaseContractService.save(purchaseContract);
        return Result.ok();
    }

    /**
     * @param contractDto
     * @return
     * @功能：修改
     */
    @RequiresPermissions("purchase:contract:update")
    @PutMapping(value = "/update")
    public Result update(@Valid @RequestBody PurchaseContractDto contractDto) {
        purchaseContractService.updateContract(contractDto);
        return Result.ok();
    }

    /**
     * @param ids
     * @return
     * @功能：批量删除
     */
    @RequiresPermissions("purchase:contract:delete")
    @DeleteMapping(value = "/delete")
    public Result delete(@RequestParam String ids) {
        if (ids == null || ids.trim().length() == 0) {
            return Result.error("ids can't be empty");
        }
        String[] idsArr = ids.split(",");
        purchaseContractService.deleteContracts(Convert.toList(Long.class, idsArr));
        return Result.ok();
    }

    /**
     * 生成合同并将可合并的订单返回
     *
     * @return
     */
    @PostMapping(value = "/gen")
    public Result genContract() {
        List<PurchaseIndentVo> purchaseIndentVos = purchaseContractService.genContract();
        return Result.ok(purchaseIndentVos);
    }

    /**
     * 查询指定审批单下的可合并订单
     *
     * @return
     */
    @GetMapping(value = "/findGenIndentBy")
    public Result findGenIndentBy(@RequestParam(required = false) Long orderId, @RequestParam(required = false) Long supplierId) {
        List<PurchaseIndentVo> purchaseIndentVos = purchaseContractService.findGenIndent(orderId, supplierId);
        return Result.ok(purchaseIndentVos);
    }

    /**
     * 合并订单
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/merge")
    public Result mergeIndent(@Valid @RequestBody PurchaseMergeContractDto dto) {
        String[] idsArr = dto.getIndentIds().split(",");
        purchaseContractService.mergeIndent(dto.getContractCode(), dto.getContractComment(), Convert.toList(Long.class, idsArr));
        return Result.ok();
    }

    /**
     * 导出付款审批单
     *
     * @param response
     * @param contractId
     * @param paymentId
     * @param exWithInvoice 导出时包含同发票的合同
     */
    @GetMapping(value = "/exportPayment")
    public void export(HttpServletResponse response, @RequestParam("contractId") Long contractId, @RequestParam(value = "paymentId", required = false) Long paymentId, @RequestParam(value = "exWithInvoice", required = false) Boolean exWithInvoice) {
        if (null == exWithInvoice) {
            exWithInvoice = false;
        }
        File exportFile = purchaseContractService.exportPayment(contractId, paymentId, exWithInvoice);
        FileUtil.setDownloadResponse(response, exportFile, exportFile.getName(), true);
    }


    /**
     * 导出采购订单
     *
     * @param response
     * @param contractId
     * @param indentId
     */
    @GetMapping(value = "/exportIndent")
    public void exportIndent(HttpServletResponse response, @RequestParam("contractId") Long contractId, @RequestParam(value = "indentId") Long indentId) {
        File exportFile = purchaseContractService.exportIndent(contractId, indentId);
        FileUtil.setDownloadResponse(response, exportFile, exportFile.getName(), true);
    }

    /**
     * 查询合同下的订单号
     *
     * @param contractId
     */
    @GetMapping(value = "/queryIndents")
    public Result exportIndent(@RequestParam("contractId") Long contractId) {
        List<PurchaseIndentSimpleVo> purchaseIndents = purchaseContractService.queryIndents(contractId);
        return Result.ok(purchaseIndents);
    }
}
